<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/26
 * Time: 16:06
 */

namespace app\admin\model;

use Exception;

/**
 * @property  int $id
 * @property  string $user_name  用户名
 * @property  string $password 密码
 * @property  string $real_name 负责人(真名)
 * @property  string $is_super 1：超级管理员，2：普通管理员',
 */
class AdminUser extends Base
{

    public static function onBeforeInsert(AdminUser $model): void
    {
        $model->password = md5($model->password . 'dt');
        $model->is_super = 2;//超级管理员
    }

    /**
     * @param AdminUser $model
     * @return void
     * @throws Exception
     */
    public static function onAfterInsert(AdminUser $model): void
    {
        self::addRole($model);
    }

    /**
     * @param AdminUser $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeUpdate(AdminUser $model): void
    {
        $model->password = md5($model->password . 'dt');
        self::addRole($model);
    }

    /**
     * @param AdminUser $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeDelete(AdminUser $model): void
    {
        if ($ids = $model->adminUserRoles()->column('id')) AdminUserRole::destroy($ids, true);//真实删除
    }


    /**
     * @param $model
     * @return void
     * @throws Exception
     */
    public static function addRole($model): void
    {
        if ($role_ids = request()->param('role_ids', 0)) {
            $arr  = explode(',', $role_ids);
            $data = [];
            foreach ($arr as $v) {
                $array['admin_role_id'] = $v;
                $array['admin_user_id'] = $model->id;
                $data[]                 = $array;
                if ($ids = $model->adminUserRoles()->column('id')) AdminUserRole::destroy($ids, true);//真实删除
                (new AdminUserRole())->saveAll($data);
            }
        }

    }
}